import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as chroma from 'chroma-js'
import type { GeoJSON } from 'leaflet'

interface MapState {
  geoJsonData: GeoJSON | null
  selectedCounty: string | null
}

export const useMapStore = defineStore('map', {
  state: (): MapState => ({
    geoJsonData: null,
    selectedCounty: null
  }),
  actions: {
    async loadGeoJsonData() {
      const response = await fetch('/assets/map-data/hubei.json')
      this.geoJsonData = await response.json()
    },
    areaStyle(feature) {
      return {
        fillColor: this.getColor(feature.properties.density),
        weight: 1,
        opacity: 1,
        color: 'white',
        fillOpacity: 0.7
      }
    },
    getColor(density) {
      return density ? chroma.scale(['#f7fbff', '#08306b'])(density / 100) : '#ccc'
    },
    onEachFeature(feature, layer) {
      layer.bindPopup(`
        <h3>${feature.properties.name}</h3>
        <p>类型: ${feature.properties.type}</p>
        <p>人口: ${feature.properties.population || '未知'}</p>
      `)
      
      layer.on({
        click: () => {
          this.selectedCounty = feature.properties.name
        }
      })
    }
  }
})